package com.blue.common.aop;

import com.alibaba.fastjson.JSON;
import com.blue.common.entity.LoginUserInfo;
import com.blue.common.utils.BusinessUtils;
import com.blue.common.utils.ThreadLocalUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
public class OperationLogsAop {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Pointcut("execution(* com.blue.controller..*.*(..))&& !@annotation(com.blue.common.annotation.IgnoreToken)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object operationLogs(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object object = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();
        LoginUserInfo loginUserInfo = ThreadLocalUtils.getLoginUserInfo();
        Map<String, Object> map = new HashMap<>();
        map.put("timeConsumption", (end - start));
        if (loginUserInfo != null) {
            map.put("requestUrl", loginUserInfo.getPath());
            map.put("params", loginUserInfo.getParams());
            map.put("operator", loginUserInfo.getUserId());
        }
        map.put("traceId", MDC.get("traceId"));
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String ip = BusinessUtils.getClientIP(request);
        map.put("ip", ip);
        rabbitTemplate.convertAndSend("operationLogsExchange", "operationLogsKey", JSON.toJSONString(map));
        return object;
    }
}
